<style lang="less">
    @import "../../../styles/table.less";
</style>
<template>
    <div class="search">

            <Row type="flex" justify="space-between" class="code-row-bg">
                <Col v-if="expand" span="5">
                    <Card title="所属维度" style="height:100%">
                    <div class="tree-bar">
                        <Tree ref="tree" :data="treeData" :load-data="loadData" @on-select-change="selectTree"></Tree>
                    </div>
                    <Spin size="large" fix v-if="treeLoading"></Spin>
                        <a href="#" slot="extra" @click.prevent="changeExpand">
                            <Tooltip content="折叠" placement="left">
                                <Icon type="md-arrow-round-back"/>
                            </Tooltip>
                        </a>
                    </Card>
                </Col>

                <Col :span="span">
                    <Card>
                    <Row>
                        <Form ref="searchForm" :model="searchForm" inline :label-width="60" class="search-form">
                            <Form-item label="题目标题" prop="examSynopsis">
                                <Input type="text" v-model="searchForm.examSynopsis" placeholder="请输入" clearable style="width: 200px"/>
                            </Form-item>
                            <Form-item label="段位等级" prop="duanLevel">
                                <Select v-model="searchForm.duanLevel" placeholder="请选择段位"    style="width: 200px">
                                    <Option value="bronze">青铜</Option>
                                    <Option value="silver">白银</Option>
                                    <Option value="gold">黄金</Option>
                                    <Option value="platinum">铂金</Option>
                                    <Option value="diamond">钻石</Option>
                                </Select>
                            </Form-item>
                            <Form-item style="margin-left:-35px;" class="br">
                                <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                                <Button @click="handleReset">重置</Button>
                            </Form-item>
                        </Form>
                    </Row>
                    <div class="left-operation-right">
                        <div>
                            <Tooltip content="请选项分类" placement="top" :disabled="!addExamBtn">
                            <Button @click="add" type="primary" :disabled="addExamBtn" icon="md-add">添加</Button>
                            </Tooltip>
                            <Button @click="delAll" icon="md-trash">批量删除</Button>
                            <Button @click="importFile" icon="md-album">导入</Button>
                            <Button @click="download" icon="md-album">下载模板</Button>
                            <Button @click="getDataList" icon="md-refresh">刷新</Button>
                            <circleLoading v-if="operationLoading"/>
                        </div>
                        <div>
                            <RadioGroup v-model="searchForm.level" @on-change="changeFileType" type="button" style="margin-right:2px">
                                <Radio label="">全部</Radio>
                                <Radio label="LT_EASY">易</Radio>
                                <Radio label="LT_MEDIUM">中</Radio>
                                <Radio label="LT_DIFFICULTY">难</Radio>
                            </RadioGroup>
                        </div>
                    </div>
                    <div v-if="showType=='list'">
                        <Row>
                            <Alert show-icon>
                                已选择 <span class="select-count">{{selectCount}}</span> 项
                                <a class="select-clear" @click="clearSelectAll">清空</a>
                            </Alert>
                        </Row>
                        <Row>
                            <Table :loading="loading" border :columns="columns" :data="data" sortable="custom" @on-sort-change="changeSort" @on-selection-change="showSelect" ref="table"></Table>
                        </Row>
                    </div>

                    <Row type="flex" justify="end" class="page">
                        <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
                    </Row>
                        <p slot="title" @click.prevent="changeExpand">
                            <Icon v-if="!expand" type="md-arrow-round-forward"/>
                            题库管理
                        </p>
                    </Card>
                </Col>

            </Row>

        <Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' width="1000" :styles="{top: '30px'}">
            <Form ref="formAdd" :model="formAdd" :label-width="70" :rules="formValidate">
                <FormItem label="题目梗概" prop="examSynopsis">
                    <Input v-model="formAdd.examSynopsis" clearable placeholder="请输入题目梗概"/>
                </FormItem>
                <FormItem label="题目难度" prop="level">
                    <Select v-model="formAdd.level" placeholder="请选择题目难度"  style="width: 200px">
                        <Option value="LT_EASY">易</Option>
                        <Option value="LT_MEDIUM">中</Option>
                        <Option value="LT_DIFFICULTY">难</Option>
                    </Select>
                </FormItem>
                <FormItem label="段位等级" prop="duanLevel">
                    <Select v-model="formAdd.duanLevel" placeholder="请选择段位"    style="width: 200px">
                        <Option value="bronze">青铜</Option>
                        <Option value="silver">白银</Option>
                        <Option value="gold">黄金</Option>
                        <Option value="platinum">铂金</Option>
                        <Option value="diamond">钻石</Option>
                    </Select>
                </FormItem>
                <FormItem label="答题限时" prop="answeringTime">
                    <InputNumber :max="30" :min="5" v-model="formAdd.answeringTime"></InputNumber>
                </FormItem>
                <FormItem label="题目标题" prop="examTitle">
                    <div ref="editor"></div>
                </FormItem>
                <Form-item label class="br">
                    <p style="color: red">建议上传图片大小不超400KB</p>
                    <Button @click="editHTML" icon="ios-create-outline">编辑HTML代码</Button>
                    <Button @click="fullscreenModal=true" icon="md-eye">预览</Button>

                </Form-item>
                <!--<FormItem v-for="(item, index) in formAdd.items" v-if="item.status" :key="index" :label="'选项 ' + item.index" :prop="'items.' + index + '.value'"  :rules="{required: true, message: '选项 ' + item.index +' 不能为空', trigger: 'blur'}">
                    <Row>
                        <Col span="15">
                        <Input type="text" v-model="item.value" placeholder="请输入选项值"></Input>
                        </Col>
                        <Col span="4" offset="1">
                        <Checkbox v-model="item.correct" >正确答案</Checkbox>
                        </Col>
                        <Col span="3" offset="1">
                        <Button @click="handleRemove(index)">删除</Button>
                        </Col>
                    </Row>
                </FormItem>
                <FormItem>
                    <Row>
                        <Col span="12">
                        <Button type="dashed" long @click="handleAdd" icon="md-add">添加选项</Button>
                        </Col>
                    </Row>
                </FormItem>-->
            </Form>
            <Upload action="/base/common/importExam" :on-success="handleSuccess"  v-show="false">
                <Button icon="ios-cloud-upload-outline" ref="upload">Upload files</Button>
            </Upload>
            <div slot="footer">
                <Button type="primary" :loading="submitLoading" @click="handelSubmit">提交</Button>
                <Button @click="modalVisible=false">取消</Button>
            </div>
        </Modal>
        <!-- html编辑 -->
        <Modal title="编辑html代码" v-model="showHTMLModal" :mask-closable="false" :width="900" :fullscreen="full">
            <Input v-if="!full" v-model="dataEdit" :autosize="true" type="textarea" style="max-height:60vh;overflow:auto"/>
            <Input v-if="full" v-model="dataEdit" :autosize="true" type="textarea"/>
            <div slot="footer">
                <Button @click="full=!full" icon="md-expand">全屏开/关</Button>
                <Button @click="editHTMLOk" type="primary" icon="md-checkmark-circle-outline">确定保存</Button>
            </div>
        </Modal>
        <Modal title="预览" v-model="fullscreenModal" fullscreen>
            <div v-html="formAdd.examTitle">{{formAdd.examTitle}}</div>
            <div slot="footer">
                <Button @click="fullscreenModal=false">关闭</Button>
            </div>
        </Modal>
        <answer-manage ref="answerManage"></answer-manage>
    </div>
</template>

<script>
    import circleLoading from "../../my-components/circle-loading.vue";
    import E from "wangeditor";
    import {sina} from "@/libs/emoji";
    import {examList,delExam,getExam, updateExam,selectExamType,addExam} from "@/api/bus";
    import {uploadFile} from "@/api/index";
    import answerManage from "./answer-manage/answerManage";

    let editor = null;
    var xss = require("xss");
    export default {
        name: "courseManage",
        components: {
            answerManage,
            circleLoading
        },
        data() {
            return {
                treeLoading: false, // 树加载状态
                index: 1,
                addExamBtn:true,
                formAdd: {
                    id:"",
                    examSynopsis:'',
                    examTitle: '',
                    level:"LT_EASY",
                    duanLevel:"bronze",
                    examTypeId:"",
                    createTime:"",
                    answeringTime: 20,
                    items: [
                        {
                            value: '',
                            index: 1,
                            status: 1,
                            correct:false
                        },
                    ]
                },
                loading: false, // 表加载状态
                editTitle: "", // 编辑节点名称
                searchKey: "", // 搜索树
                expand: true,
                fileType: "all",
                showType: "list",//数据展示方式
                span: 19,
                expandIcon: "ios-arrow-back",
                selectNode: {},
                treeData: [], // 树数据
                operationLoading: false, // 操作加载状态
                selectCount: 0, // 多选计数
                selectList: [], // 多选数据
                searchForm: {
                    // 搜索框对应data对象
                    examSynopsis: "",
                    examTypeId:-1,
                    level: "",
                    pageNumber: 1, // 当前页数
                    pageSize: 10, // 页面大小
                    sort: "createTime", // 默认排序字段
                    order: "desc" // 默认排序方式
                },
                modalType: 0, // 添加或编辑标识
                modalVisible: false, // 添加或编辑显示
                modalTitle: "", // 添加或编辑标题
                formValidate: {
                    // 表单验证规则
                    examSynopsis: [{required: true, message: "不能为空", trigger: "blur"}],
                    examTitle: [{required: true, message: "不能为空", trigger: "blur"}]
                },
                columns: [
                    // 表头
                    {
                        type: "selection",
                        width: 60,
                        align: "center",
                        fixed: "left"
                    },
                    {
                        type: "index",
                        width: 60,
                        align: "center",
                        fixed: "left"
                    },
                    {
                        title: "题目名称",
                        key: "examSynopsis",
                        width: 300,
                        ellipsis:true,
                        tooltip:true,
                        sortable: true,
                        fixed: "left"
                    },
                    {
                        title: "所属维度",
                        key: "examTypeName",
                        width: 120,
                        sortable: true
                    },
                    {
                        title: "段位等级",
                        key: "duanLevel",
                        width: 120,
                        sortable: true,
                        render: (h, params) => {
                            let re = "";
                            if (params.row.duanLevel === 'bronze') {
                                return h("div", [
                                    h(
                                        "Tag",
                                        {
                                            props: {
                                                color: "#19be6b"
                                            }
                                        },
                                        "青铜"
                                    )
                                ]);
                            } else if (params.row.duanLevel === 'silver') {
                                return h("div", [
                                    h(
                                        "Tag",
                                        {
                                            props: {
                                                color: "#ff9900"
                                            }
                                        },
                                        "白银"
                                    )
                                ]);
                            }else if (params.row.duanLevel === 'gold') {
                                return h("div", [
                                    h(
                                        "Tag",
                                        {
                                            props: {
                                                color: "#ed4014"
                                            }
                                        },
                                        "黄金"
                                    )
                                ]);
                            }else if (params.row.duanLevel === 'platinum') {
                                return h("div", [
                                    h(
                                        "Tag",
                                        {
                                            props: {
                                                color: "#ed4014"
                                            }
                                        },
                                        "铂金"
                                    )
                                ]);
                            }else if (params.row.duanLevel === 'diamond') {
                                return h("div", [
                                    h(
                                        "Tag",
                                        {
                                            props: {
                                                color: "#ed4014"
                                            }
                                        },
                                        "钻石"
                                    )
                                ]);
                            }
                        }
                    },
                    {
                        title: "题目难度",
                        key: "level",
                        width: 120,
                        sortable: true,
                        render: (h, params) => {
                            let re = "";
                            if (params.row.level === 'LT_EASY') {
                                return h("div", [
                                    h(
                                        "Tag",
                                        {
                                            props: {
                                                color: "#19be6b"
                                            }
                                        },
                                        "易"
                                    )
                                ]);
                            } else if (params.row.level === 'LT_MEDIUM') {
                                return h("div", [
                                    h(
                                        "Tag",
                                        {
                                            props: {
                                                color: "#ff9900"
                                            }
                                        },
                                        "中"
                                    )
                                ]);
                            }else if (params.row.level === 'LT_DIFFICULTY') {
                                return h("div", [
                                    h(
                                        "Tag",
                                        {
                                            props: {
                                                color: "#ed4014"
                                            }
                                        },
                                        "难"
                                    )
                                ]);
                            }
                        }
                    },
                    {
                        title: "答题次数",
                        key: "frequency",
                        width: 120,
                        sortable: true,
                        render: (h, params) => {
                            let re = params.row.frequency
                            if(re == ''){
                                re = 0
                            }
                            return h("div", re);
                        }
                    },
                    /*{
                        title: "正确次数",
                        key: "examTrue",
                        width: 120,
                        sortable: true
                    },
                    {
                        title: "错误次数",
                        key: "examfalse",
                        width: 120,
                        sortable: true
                    },*/
                    {
                        title: "正确率",
                        key: "accuracy",
                        width: 120,
                        sortable: true,
                        render: (h, params) => {
                            let re = params.row.accuracy+"%";
                            return h("div", re);
                        }
                    },
                    {
                        title: "创建时间",
                        key: "createTime",
                        width: 200,
                        sortable: true,
                        sortType: "desc"
                    },
                    {
                        title: "操作",
                        key: "action",
                        width: 200,
                        align: "center",
                        fixed: "right",
                        render: (h, params) => {
                            return h("div", [
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "primary",
                                            size: "small"
                                        },
                                        style: {
                                            marginRight: "5px"
                                        },
                                        on: {
                                            click: () => {
                                                this.edit(params.row);
                                            }
                                        }
                                    },
                                    "编辑"
                                ),
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "error",
                                            size: "small"
                                        },
                                        style: {
                                            marginRight: "5px"
                                        },
                                        on: {
                                            click: () => {
                                                this.remove(params.row);
                                            }
                                        }
                                    },
                                    "删除"
                                ),
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "info",
                                            size: "small"
                                        },
                                        on: {
                                            click: () => {
                                                this.answer(params.row);
                                            }
                                        }
                                    },
                                    "答案"
                                )
                            ]);
                        }
                    }
                ],
                submitLoading: false, // 添加或编辑提交状态
                data: [], //表单数据
                total: 0,// 表单数据总数
                dataEdit: '',
                showHTMLModal: false, // 显示html
                full: false, // html全屏开关
                fullscreenModal: false// 显示全屏预览
            };
        },
        methods: {
            init() {
                this.getTreeData();
                // 获取表单数据
                this.getDataList();
                this.initEditor();
            },
            answer(v) {
                this.$refs.answerManage.showDrawer(v);
            },
            initEditor() {
                let that = this;
                editor = new E(this.$refs.editor);
                editor.customConfig.onchange = html => {
                    this.formAdd.examTitle = html;
                };
                editor.customConfig.uploadImgServer = uploadFile;
                editor.customConfig.uploadImgHeaders = {
                    Authorization: that.getStore("accessToken")
                };
                editor.customConfig.uploadFileName = "file";
                editor.customConfig.uploadImgHooks = {
                    before: function (xhr, editor, files) {
                    },
                    success: function (xhr, editor, result) {
                    },
                    fail: function (xhr, editor, result) {
                        that.$Message.error("上传图片失败");
                    },
                    error: function (xhr, editor) {
                        that.$Message.error("上传图片出错");
                    },
                    timeout: function (xhr, editor) {
                        that.$Message.error("上传图片超时");
                    },
                    customInsert: function (insertImg, result, editor) {
                        if (result.status === true) {
                            let url = result.data.fileUrl;
                            insertImg(url);
                            that.$Message.success("上传图片成功");
                        } else {
                            that.$Message.error(result.info);
                        }
                    }
                };
                editor.customConfig.fontNames = ["微软雅黑", "宋体", "黑体", "Arial"];
                editor.customConfig.emotions = [
                    {
                        title: "新浪",
                        type: "image",
                        content: sina
                    }
                ];
                editor.create();
            },
            editHTML() {
                this.dataEdit = this.formAdd.examTitle;
                this.showHTMLModal = true;
            },
            editHTMLOk() {
                editor.txt.html(this.dataEdit);
                this.formAdd.examTitle = xss(this.dataEdit);
                this.showHTMLModal = false;
            },
            getDataList() {
                this.loading = true;
                // 根据用户选择树加载表数据
                examList(this.searchForm).then(res => {
                    this.loading = false;
                    if (res.status === true) {
                        this.data = res.data.rows;
                        this.total = res.data.total;
                    }
                });

            },
            addDcit(){},
            handleDropdown(){},
            changeFileType(){
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.getDataList();
            },
            handleAdd () {
                this.index++;
                this.formAdd.items.push({
                    value: '',
                    index: this.index,
                    status: 1,
                    correct:0
                });
            },
            download(v) {
                location.href = "../模板.xlsx";
            },
            handleRemove (index) {
                this.formAdd.items[index].status = 0;
                this.formAdd.items.splice(index, 1);
                this.index--;
            },
            //加载一级课程类型
            getTreeData() {
                this.treeLoading = true;
                selectExamType({parentId:0}).then(res => {
                    this.treeLoading = false;
                    if (res.status === true) {
                        this.treeData = res.data;
                    }
                });
            },
            //加载二级课程类型
            loadData(item, callback) {
                selectExamType({parentId:item.id}).then(res => {
                    if (res.status === true) {
                        callback(res.data);
                    }
                });
            },
            search() {
                // 搜索树
                if (this.searchKey) {

                }

            },
            selectTree(v) {
                if (v.length > 0) {
                    let str = JSON.stringify(v[0]);
                    let data = JSON.parse(str);
                    this.selectNode = data;
                    this.searchForm.examTypeId = this.selectNode.id;
                    if (this.selectNode.isParent==1) {
                        this.formAdd.examTypeId=data.id;
                        this.addExamBtn = false;
                    }
                    this.editTitle = data.title;
                    // 重新加载表
                    this.getDataList();
                } else {
                    this.cancelEdit();
                }
            },
            cancelEdit() {
                let data = this.$refs.tree.getSelectedNodes()[0];
                if (data) {
                    data.selected = false;
                }
                // 取消选择后获取全部数据
                this.selectNode = {};
                this.editTitle = "";
                this.getDataList();
            },
            importFile() {
                this.$refs.upload.$el.click()
            },
            handleSuccess(res, file) {
                if(res.code == 200){
                    this.getDataList();
                }else{

                }
            },
            changeSelect(v) {
                this.selectCount = v.length;
                this.selectList = v;
            },
            changeExpand() {
                this.expand = !this.expand;
                if (this.expand) {
                    this.expandIcon = "ios-arrow-back";
                    this.span = 19;
                } else {
                    this.expandIcon = "ios-arrow-forward";
                    this.span = 24;
                }
            },
            changePage(v) {
                this.searchForm.pageNumber = v;
                this.getDataList();
                this.clearSelectAll();
            },
            changePageSize(v) {
                this.searchForm.pageSize = v;
                this.getDataList();
            },
            changeShowType() {
                this.searchForm.pageNumber = 1;
                if (this.showType == "list") {
                    this.searchForm.pageSize = 5;
                } else {
                    this.searchForm.pageSize = 12;
                }
                this.getDataList();
            },
            handleSearch() {
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.getDataList();
            },
            handleReset() {
                this.$refs.searchForm.resetFields();
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                // 重新加载数据
                this.getDataList();
            },
            changeSort(e) {
                this.searchForm.sort = e.key;
                this.searchForm.order = e.order;
                if (e.order === "normal") {
                    this.searchForm.order = "";
                }
                this.getDataList();
            },
            showSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            clearSelectAll() {
                this.$refs.table.selectAll(false);
            },
            add() {
                this.modalType = 0;
                this.modalTitle = "添加";
                this.$refs.formAdd.resetFields();
                this.modalVisible = true;
                editor.txt.html('');
            },
            edit(v) {
                this.modalType = 1;
                this.modalTitle = "编辑题目";
                this.$refs.formAdd.resetFields();
                this.formAdd.id=v.id;
                getExam(this.formAdd.id).then(res => {
                    if (res.status === true) {
                        var examItems=res.data.examItems;
                        delete res.data.examItems;
                        res.data.items=JSON.parse(examItems);
                        res.data.answeringTime = parseInt(res.data.answeringTime)
                        this.formAdd =res.data;
                        this.index=res.data.items.length;
                        this.modalVisible = true;
                        editor.txt.html(this.formAdd.examTitle);
                    }
                });
            },
            handelSubmit() {
                this.$refs.formAdd.validate(valid => {
                    if (valid) {
                        this.submitLoading = true;
                        this.formAdd.examItems=JSON.stringify(this.formAdd.items);
                        if (this.modalType === 0) {
                            // 添加 避免编辑后传入id等数据 记得删除
                            delete this.formAdd.id;
                            delete this.formAdd.status;
                            addExam(this.formAdd).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("添加成功");
                                    this.getDataList();
                                    this.modalVisible = false;
                                }
                            });
                        } else if (this.modalType === 1) {
                            updateExam(this.formAdd).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("修改成功");
                                    this.getDataList();
                                    this.modalVisible = false;
                                }
                            });
                        }
                    }
                });
            },
            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除",
                    // 记得确认修改此处
                    content: "您确认要删除?",
                    onOk: () => {
                        delExam(v.id).then(res => {
                            if (res.status === true) {
                                this.$Message.success("删除成功");
                                this.getDataList();
                            }
                        });
                    }
                });
            },
            delAll() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要删除的数据");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids.push(e.id);
                        });
                        delExam(ids).then(res => {
                            if (res.status === true) {
                                this.$Message.success("删除成功");
                                this.clearSelectAll();
                                this.getDataList();
                            }
                        });
                    }
                });
            }
        },
        mounted() {
            this.init();
        }
    };
</script>